package aad.storyboard.controller;

import java.util.ArrayList;

import aad.storyboard.model.Animation;
import aad.storyboard.model.AnimationProvider;
import aad.storyboard.model.GraphicalObject;
import aad.storyboard.model.Image;
import aad.storyboard.model.InfoAnimation;
import aad.storyboard.model.Layer;
import aad.storyboard.model.Scene;
import aad.storyboard.model.Story;
import aad.storyboard.view.GraphicView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class ViewTouchListener implements OnTouchListener{
	
	private Story story;
	private GraphicView view;
	

	public ViewTouchListener(Story s){
		story = s;
		view=(GraphicView) GUIComposer.getInstance().getGraphicalView();

	}
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		
		Integer key = new Integer(AnimationProvider.EVENT_TOUCH);
		ArrayList<Animation> touchAnimations = AnimationProvider.getInstance().getOnEventAnimations().get(key);
		if(touchAnimations != null){
			for(Animation a : touchAnimations){
				for(Image img : a.getImages()){
					
					if(story.getCurrentChapter().getCurrentScene().containsImage(img.getName())){
						System.out.println("ONTouch2");
						if(event.getX()>= img.getPosX() && event.getX() <= img.getPosX()+img.getWidth()){
							if(event.getY()>= img.getPosY() && event.getY() <= img.getPosY()+img.getHeight()){
								//check
								
									int executionTime = StoryTimer.getInstance().getCurrentTime();
									Log.e("TAG", "FOUND ANIMATION TO STRT"+a);
									if (a instanceof InfoAnimation)
										{
										((InfoAnimation)a).setText(img.getInfo());
										((InfoAnimation)a).setCurrentImage(img);
										((InfoAnimation)a).setTouched(true);
										}
									a.start();
									ControllerManager.getInstance().getFRC().addObserver(a);
									AnimationProvider.getInstance().addAnimationToStack(a);
									break;
							}
						}	
					}
				}
			}
		}
		
		//Drag & Drop
		//ToDo: position determination does not work yet
		
		//view.setDragging(true);

		Integer key1 = new Integer(AnimationProvider.EVENT_DRAG);
		ArrayList<Animation> dragAnimations = AnimationProvider.getInstance().getOnEventAnimations().get(key1);
		if(dragAnimations != null){
			for(Animation a : dragAnimations){
				for(Image img : a.getImages()){
					if(story.getCurrentChapter().getCurrentScene().containsImage(img.getName())){
						if(event.getX()>= img.getPosX() && event.getX() <= img.getPosX()+img.getWidth()){
							if(event.getY()>= img.getPosY() && event.getY() <= img.getPosY()+img.getHeight()){
								//check
									int executionTime = StoryTimer.getInstance().getCurrentTime();
									Log.e("TAG", "FOUND ANIMATION TO STRT"+a);
									a.start();
									ControllerManager.getInstance().getFRC().addObserver(a);
									AnimationProvider.getInstance().addAnimationToStack(a);
									break;
							}
						}	
					}
				}
			}
		}
		return false;
	}

}
